package com.roy.springboot.product;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.core.AsyncAmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class ProductController {

   // @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AsyncRabbitTemplate asyncRabbitTemplate;


    @RequestMapping("/send2/{num}/{msg1}/{msg2}")
    @ResponseBody
    public String send2(@PathVariable int num, @PathVariable String msg1, @PathVariable String msg2){
        System.out.println("---rabbitmq send2 start---");


        List<MessageTemp> messages =new ArrayList<>();

        for (int i = 1; i <= num ; i++) {
            MessageTemp m1 = new MessageTemp();
            m1.setMessage_id(i);
            m1.setAmount(20+i);
            m1.setState(i+msg1);
            m1.setUser_id(i+msg2);
            messages.add(m1);
        }

        System.out.println("====2===messages===confirm===:" + JSONObject.toJSONString(messages));
        for (MessageTemp message : messages) {
            //rabbitTemplate.convertAndSend("exchange.message2", "chenfl.message.routeKey2-gy", JSONObject.toJSONString(message).getBytes());
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
            asyncRabbitTemplate.convertSendAndReceive("exchange.message2", "chenfl.message.routeKey2-guyi", JSONObject.toJSONString(message));
            //会导致消息确认的回调出现问题，所有加段延时
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }



        return  "send2 message !";
    }
}
